package com.ten.mall.controller;

import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ten.mall.config.WeChatConfig;
import com.ten.mall.service.AddressService;
import com.ten.mall.service.CartService;
import com.ten.mall.service.ItemOrderService;
import com.ten.mall.service.ItemService;
import com.ten.mall.service.UserService;
import com.ten.mall.service.YaodianService;
import com.ten.mall.utils.CodeUtils;
import com.ten.mall.utils.CommonUtis;
import com.ten.mall.utils.HttpClientUtil;
import com.ten.mall.utils.Httpsrequest;
import com.ten.mall.utils.MessageUtil;
import com.ten.mall.utils.PayUtil;
import com.ten.mall.utils.Sign;
import com.ten.mall.utils.WeiXinUtils;
import com.ten.mall.vo.Address;
import com.ten.mall.vo.Cart;
import com.ten.mall.vo.DianyuanOrderVo;
import com.ten.mall.vo.Item;
import com.ten.mall.vo.ItemOrder;
import com.ten.mall.vo.MyResult;
import com.ten.mall.vo.OrderReturnVo;
import com.ten.mall.vo.OrderVo;
import com.ten.mall.vo.TimeVo;
import com.ten.mall.vo.User;
import com.ten.mall.vo.Yaodian;
import com.ten.mall.vo.weixin.AccessToken;
import com.ten.mall.vo.weixin.Pay;
import com.ten.mall.vo.weixin.RefusePay;
import com.ten.mall.vo.weixin.TemplateData;
import com.ten.mall.vo.weixin.WebAuthorToken;

@Controller
public class ItemOrderController {
	@Value("${weixin_token}")
	private String token;
	@Value("${app_secret}")
	private String appSecret;
	@Value("${weixin_appid}")
	private String appId;
	@Value("${mch_id}")
	private String mchId;
	@Value("${key}")
	private String key;
	@Value("${service_ip}")
	private String serviceIp;// notify_url
	@Value("${notify_url}")
	private String notify_url;
	@Value("${server_name}")
	private String server_name;
	@Value("${template_id}")
	private String template_id;
	@Autowired
	private ItemOrderService itemOrderService;
	@Autowired
	private ItemService itemService;

	@Autowired
	private AddressService addressService;

	@Autowired
	private YaodianService yaodianService;

	@Autowired
	private UserService userService;
	@Autowired
	private CartService cartService;
	private Logger log = LoggerFactory.getLogger(ItemOrderController.class);

	/**
	 * 增加订单
	 * 
	 * @param file
	 * @param itemOrder
	 * @param request
	 * @return
	 */
	@RequestMapping("/phone/creatOrder")
	@ResponseBody
	public String uploadOrder(ItemOrder itemOrder,HttpServletRequest request) {
		String result = "";
		User u = (User) request.getSession().getAttribute("u");
		try {
			if (u != null) {
				itemOrder.setOrderOwner(u.getId());
				itemOrder.setOrderDoctor(u.getRemark());
				itemOrder.setOrderState(1);
			
				if(StringUtils.isBlank(itemOrder.getOrderYuliu())){
					User user =userService.selectById(u.getRemark());
					if(user==null){
						itemOrder.setOrderSaleman(u.getRemark());
						itemOrder.setOrderDoctor(u.getId());
					}else{
						itemOrder.setOrderSaleman(user.getRemark());
					}
				}else{
					Yaodian yao =yaodianService.selectById(Integer.parseInt(itemOrder.getOrderYuliu()));
					itemOrder.setOrderSaleman(yao.getHouseRemark());
					itemOrder.setOrderAddress(null);
				}
			}
			itemOrderService.creatOrder(itemOrder);
			result = itemOrder.getId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 购物车创建订单
	 * @param itemOrder
	 * @param request
	 * @return
	 */
	@RequestMapping("/phone/creatCartOrder")
	@ResponseBody
	public String creatCartOrder(ItemOrder itemOrder,HttpServletRequest request,String ids) {
		String result = "";
		List<ItemOrder> list =new ArrayList<>();
		User u = (User) request.getSession().getAttribute("u");
		try {
			if (u != null) {
				if(StringUtils.isNotBlank(ids)&&ids.endsWith(",")){
					String str[] =ids.substring(0,ids.length()-1).split(",");
					for(String id :str){
						ItemOrder order =itemOrderService.selectById(id);
						order.setOrderOwner(u.getId());
						order.setOrderDoctor(u.getRemark());
						order.setOrderState(1);
						order.setChufangPic(itemOrder.getChufangPic());
						order.setOrderDetail(itemOrder.getOrderDetail());
						if(StringUtils.isBlank(itemOrder.getOrderYuliu())){
							order.setOrderAddress(itemOrder.getOrderAddress());
							User user =userService.selectById(u.getRemark());
							if(user==null){
								order.setOrderSaleman(u.getRemark());
								order.setOrderDoctor(u.getId());
							}else{
								order.setOrderSaleman(user.getRemark());
							}
						}else{
							Yaodian yao =yaodianService.selectById(Integer.parseInt(itemOrder.getOrderYuliu()));
							order.setOrderSaleman(yao.getHouseRemark());
							order.setOrderRemark(itemOrder.getOrderRemark());
							order.setOrderYuliu(itemOrder.getOrderYuliu());
						}
						list.add(order);
					}
					
				}
			}
			for(ItemOrder o:list){
				itemOrderService.creatOrder(o);
				result =o.getOrderPrepare();
			}
			
			//result = itemOrder.getId();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 订单支付页面
	 * 
	 * @param id
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/orderPay")
	public String orderPay(String id, HttpServletRequest res) {
		ItemOrder itemOrder = itemOrderService.selectById(id);
		String mybody = itemOrder.getGoodsName() + "-公众号网页支付";
		res.setAttribute("order", itemOrder);
		User u = (User) res.getSession().getAttribute("u");
		String nonce_str = PayUtil.getRandomString(20);
		String prepay_id = "";
		Integer total_fee = PayUtil.changeToFen(itemOrder.getOrderTotal());
		if (u != null) {
			prepay_id = pay(u.getName(), itemOrder.getId(), nonce_str, mybody, total_fee);
		}
		log.info("prepay_id:" + prepay_id);
		String timeStamp = PayUtil.getTempStamp();
		String prepayId = "prepay_id=" + prepay_id;
		SortedMap<Object, Object> h5parameter = new TreeMap<Object, Object>();
		h5parameter.put("appId", appId);
		h5parameter.put("timeStamp", timeStamp);
		h5parameter.put("nonceStr", nonce_str);
		h5parameter.put("package", prepayId);
		h5parameter.put("signType", "MD5");

		String paySign = Sign.creatSign(h5parameter, key);
		log.info("paySign:" + paySign);
		res.setAttribute("appId", appId);
		res.setAttribute("timeStamp", timeStamp);
		res.setAttribute("nonceStr", nonce_str);
		res.setAttribute("prepayId", prepayId);
		res.setAttribute("paySign", paySign);
		return "phone/orderPay";
	}
	/**
	 * 购物车购物支付
	 * @param id
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/orderCartPay")
	public String orderCartPay(String id, HttpServletRequest res) {
		if(StringUtils.isNotBlank(id)){
			List<ItemOrder> list = itemOrderService.selectByPrapare(id);
			BigDecimal sum =new BigDecimal(0);
			if(list!=null&&list.size()>0){
				for(ItemOrder i:list){
					sum =sum.add(i.getOrderTotal());
				}
				String mybody ="公众号网页支付";
				User u = (User) res.getSession().getAttribute("u");
				String nonce_str = PayUtil.getRandomString(20);
				String prepay_id = "";
				Integer total_fee = PayUtil.changeToFen(sum);
				if (u != null) {
					prepay_id = pay(u.getName(), id, nonce_str, mybody, total_fee);
				}
				log.info("prepay_id:" + prepay_id);
				String timeStamp = PayUtil.getTempStamp();
				String prepayId = "prepay_id=" + prepay_id;
				SortedMap<Object, Object> h5parameter = new TreeMap<Object, Object>();
				h5parameter.put("appId", appId);
				h5parameter.put("timeStamp", timeStamp);
				h5parameter.put("nonceStr", nonce_str);
				h5parameter.put("package", prepayId);
				h5parameter.put("signType", "MD5");
				String paySign = Sign.creatSign(h5parameter, key);
				log.info("paySign:" + paySign);
				res.setAttribute("appId", appId);
				res.setAttribute("timeStamp", timeStamp);
				res.setAttribute("nonceStr", nonce_str);
				res.setAttribute("prepayId", prepayId);
				res.setAttribute("paySign", paySign);
			}
			res.setAttribute("sum", sum);
			res.setAttribute("id", id);
		}
		return "phone/orderCartPay";
	}

	/**
	 * 后台查看用户
	 * 
	 * @param start
	 * @param size
	 * @param res
	 * @param vo
	 * @return
	 */
	@RequestMapping("/admin/orderList")
	public String orderList(@RequestParam(name = "start", defaultValue = "1") Integer start,
			@RequestParam(name = "size", defaultValue = "10") Integer size, HttpServletRequest res, OrderVo vo) {
		if(vo.getState()==null){
			vo.setState(2);
		}
		if(vo.getState()==20){
			vo.setState(null);
		}
		Map<String,Object> map = itemOrderService.selectByPages(start, size, vo);
		List<OrderReturnVo> list =(List<OrderReturnVo>) map.get("list");
		res.setAttribute("list", list);
		Long mySize = (Long) map.get("total");
		int total =mySize.intValue()/10 +1;
		res.setAttribute("page", start);
		res.setAttribute("total", total);
		return "jsp/orderList";
	}

	/**
	 * 改变产品的状态
	 * 
	 * @param state
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin/stateChange")
	@ResponseBody
	public String stateChange(ItemOrder order) {
		String rs = "error";
		if (StringUtils.isNotBlank(order.getId())) {
			try {
				itemOrderService.updataOrder(order);
				rs = "ok";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rs;
	}

	/**
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/admin/orderState")
	public String orderState(String id, Model model) {
		if (StringUtils.isNotBlank(id)) {
			ItemOrder itemOrder = itemOrderService.selectById(id);
			model.addAttribute("order", itemOrder);
		}
		return "jsp/orderState";
	}

	/**
	 * 删除订单
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin/orderDel")
	@ResponseBody
	public String orderDel(String id) {
		String ss = "error";
		if (StringUtils.isNotBlank(id)) {
			try {
				itemOrderService.deleteOrder(id);
				ss = "ok";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ss;
	}
	/**
	 * 前端删除订单
	 * @param id
	 * @return
	 */
	@RequestMapping("/phone/orderDel")
	@ResponseBody
	public String phoneDelOrder(String id){
		String ss = "error";
		if (StringUtils.isNotBlank(id)) {
			try {
				itemOrderService.deleteOrder(id);
				ss = "ok";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ss;
	}
	/**
	 * 生产订单
	 * 
	 * @param id
	 * @param storage
	 * @param list
	 * @return
	 */
	@RequestMapping("/phone/addOrder")
	@ResponseBody
	public String addOrder(Integer id, Integer storage, String list) {
		String rs = "error";
		ItemOrder itemOrder = new ItemOrder();
		if (id != null) {
			Item item = itemService.selectById(id);
			if (item != null) {
				itemOrder.setGoodsId(item.getId());
				itemOrder.setGoodsPic(item.getGoodsPic());
				itemOrder.setOrderSum(storage);
				itemOrder.setOrderPrice(item.getGoodsPrice());
				itemOrder.setOrderMonth(PayUtil.getMonth());
				itemOrder.setGoodsName(item.getGoodsName());
				itemOrder.setOrderPrepare(list);
				itemOrder.setOrderState(0);
			}
			try {
				rs = itemOrderService.insertOrder(itemOrder);
				// rs="ok";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rs;
	}

	/**
	 * 确认订单
	 * 
	 * @param id
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/toOrder")
	public String toOrder(String id, HttpServletRequest res) {
		if (StringUtils.isNotBlank(id)) {
			ItemOrder itemOrder = itemOrderService.selectById(id);
			Item item = itemService.selectById(itemOrder.getGoodsId());
			res.setAttribute("order", itemOrder);
			res.setAttribute("item", item);
			User u = (User) res.getSession().getAttribute("u");
			if (u != null) {
				Address address = addressService.selectByState(u.getId(), 1);
				res.setAttribute("address", address);
			}
			String ss = itemOrder.getOrderYuliu();
			if (StringUtils.isNotBlank(ss)) {
				Yaodian yaodian = yaodianService.selectById(Integer.parseInt(ss));
				res.setAttribute("yaodian", yaodian);
			}
		}
		return "/phone/order";
	}
	/**
	 * 购物车购买药品
	 * @param ids
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/cartToOder")
	public String cartToOder(String ids, HttpServletRequest res){
		List<ItemOrder> orders =new ArrayList<>();
		if(StringUtils.isNotBlank(ids)){
			String [] str =ids.substring(0,ids.length()-1).split(",");
			for(String id:str){
				ItemOrder itemOrder = itemOrderService.selectById(id);
				orders.add(itemOrder);
			}
		}
		res.setAttribute("list", orders);
		return "";
	}
	/**
	 * 购物车确认订单
	 * @param id
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/toCartOrder")
	public String toCartOrder(String ids, HttpServletRequest res) {
		List<ItemOrder> list =new ArrayList<>();
		String ss="";
		BigDecimal sum =new BigDecimal(0);
		if (StringUtils.isNotBlank(ids)&&(ids.endsWith(","))) {
			String str[] =ids.substring(0,ids.length()-1).split(",");
			for(String id:str){
				ItemOrder itemOrder = itemOrderService.selectById(id);
				ss=itemOrder.getOrderYuliu();
				sum =sum.add(itemOrder.getOrderTotal());
				list.add(itemOrder);
			}
			res.setAttribute("list", list);
			User u = (User) res.getSession().getAttribute("u");
			if (u != null) {
				Address address = addressService.selectByState(u.getId(), 1);
				res.setAttribute("address", address);
			}
			if (StringUtils.isNotBlank(ss)) {
				Yaodian yaodian = yaodianService.selectById(Integer.parseInt(ss));
				res.setAttribute("yaodian", yaodian);
			}
		}
		res.setAttribute("sum", sum);
		res.setAttribute("ids", ids);
		return "/phone/cartOrder";
	}
	/**
	 * 上传图片
	 * 
	 * @param file
	 * @param res
	 * @return
	 */
	@RequestMapping("/phone/upload")
	@ResponseBody
	public String upLoadFile(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest res) {
		String path = res.getSession().getServletContext().getRealPath("/fang");
		String fileName =new Date().getTime()+file.getOriginalFilename();
		File newFile = new File(path, fileName);
		try {
			file.transferTo(newFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("文件上传失败!");
		}
		return "/fang/" + fileName;
	}

	/**
	 * 调用统一认证，得到时间戳!
	 * 
	 * @param openid
	 * @return
	 */
	private String pay(String openid, String orderId, String nonce_str, String myBody, Integer total_fee) {
		// String notify_url ="http://myweixin.s3.natapp.cc/phone/callback";
		// 订单号码
		SortedMap<Object, Object> parameters = new TreeMap<>();
		parameters.put("appid", appId);
		parameters.put("body", myBody);// 描述
		parameters.put("mch_id", mchId);
		parameters.put("nonce_str", nonce_str);
		parameters.put("notify_url", notify_url);
		parameters.put("out_trade_no", orderId);
		parameters.put("openid", openid);
		parameters.put("spbill_create_ip", serviceIp);
		parameters.put("trade_type", "JSAPI");
		parameters.put("total_fee", total_fee);// 支付金额
		String sign = Sign.creatSign(parameters, key);
		Pay pay = new Pay();
		pay.setAppid(appId);
		pay.setBody(myBody);
		pay.setMch_id(mchId);
		pay.setNonce_str(nonce_str);
		pay.setNotify_url(notify_url);
		pay.setOpenid(openid);
		pay.setSign(sign);
		pay.setOut_trade_no(orderId);
		pay.setSpbill_create_ip(serviceIp);
		pay.setTrade_type("JSAPI");
		pay.setTotal_fee(total_fee);
		String xml = MessageUtil.objectToXml(pay).replaceAll("__", "_");
		log.info("xml:" + xml);
		String requestUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		String respxml = null;
		String prepay_id = null;
		try {
			respxml = Httpsrequest.HttpsRequest(requestUrl, "POST", xml);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Document doc = DocumentHelper.parseText(respxml);
			Element root = doc.getRootElement();
			List<Element> elementList = root.elements();
			for (int i = 0; i < elementList.size(); i++) {
				if (elementList.get(i).getName().equals("prepay_id")) {

					prepay_id = elementList.get(i).getTextTrim();

				}

			}

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return prepay_id;
	}

	/**
	 * 订单支付返回
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/phone/callback")
	public void huiDiao(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String out_trade_no = null;
		String return_code = null;
		Map<String, String> resultMap;
		resultMap = MessageUtil.xmlToMap(request);
		//String transaction_id = (String) resultMap.get("transaction_id");
		out_trade_no = (String) resultMap.get("out_trade_no");
		return_code = (String) resultMap.get("return_code");
		log.info("success:" + return_code);
		if ("SUCCESS".equals(return_code) && StringUtils.isNotBlank(out_trade_no)) {
			ItemOrder itemOrder = itemOrderService.selectById(out_trade_no);
			if(itemOrder!=null){
				if (itemOrder.getOrderState()==1) {
					itemOrder.setOrderState(2);
					if (StringUtils.isNotBlank(itemOrder.getOrderYuliu())) {
						Map<String, Integer> map = new HashMap<>();
						map.put("yaoStorage", itemOrder.getOrderSum());
						map.put("yaoId", Integer.parseInt(itemOrder.getOrderYuliu()));
						map.put("goodsId", itemOrder.getGoodsId());
						String path = request.getSession().getServletContext().getRealPath("/code") + "/"
								+ itemOrder.getId() + ".png";
						String content = server_name + "/orderTake?orderId=" + itemOrder.getId();
						String directUrl = WeiXinUtils.createMyEncodeUrl(appId, content);
						CodeUtils.createQcode(directUrl, path);
						itemOrder.setOrderTest("/code/"+itemOrder.getId() + ".png");
						itemOrderService.updateYaodianKucun(map, itemOrder);
						log.info("药店库存:" + 11);

					} else {
						itemOrderService.crateOrderUpdateItem(itemOrder);
						log.info("电商库存:" + 12);
					}
				}
			}/*else{
				List<ItemOrder> list =itemOrderService.selectByPrapare(out_trade_no);
				if(list.get(0).getOrderState()==1){
					if(StringUtils.isNotBlank(list.get(0).getOrderYuliu())){
						String path = request.getSession().getServletContext().getRealPath("/code") + "/"
								+ out_trade_no + ".png";
						String content = server_name + "/orderTake?orderId=" + out_trade_no;
						String directUrl = WeiXinUtils.createMyEncodeUrl(appId, content);
						CodeUtils.createQcode(directUrl, path);
					}
				}
			}*/
		}
		log.info("result_code");
		request.setAttribute("out_trade_no", out_trade_no);
		// 通知微信.异步确认成功.必写.不然微信会一直通知后台.八次之后就认为交易失败了.
		response.setContentType("text/xml;charset=utf-8");
		String xml = "<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		response.getWriter().write(xml);
	}

	/**
	 * 申请退款界面
	 * 
	 * @param res
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/phone/refuseOrder")
	public String refuseOrder(HttpServletRequest res, String orderId) throws Exception {
		String rs = "/phone/refuse_error";
		if (StringUtils.isNotBlank(orderId)) {
			ItemOrder itemOrder = itemOrderService.selectById(orderId);
			if(itemOrder.getOrderState()==2||itemOrder.getOrderState()==8){
				String path = res.getSession().getServletContext().getRealPath("/WEB-INF/cert");
				File f = new File(path, "apiclient_cert.p12");
				RefusePay refuse = new RefusePay();
				refuse.setAppid(appId);
				refuse.setKey(key);
				refuse.setMch_id(mchId);
				refuse.setOut_trade_no(itemOrder.getId());
				Integer total_fee = PayUtil.changeToFen(itemOrder.getOrderTotal());
				refuse.setTotal_fee(String.valueOf(total_fee));
				refuse.setRefund_fee(String.valueOf(total_fee));
				refuse.setOut_refund_no(PayUtil.createRefuseId(itemOrder.getId()));
				String data = WeChatConfig.wxPayRefund(refuse);
				log.info("data:" + data);
				String result = WeChatConfig.wxPayBack(data, mchId, f);
				log.info("result:" + result);
				Map<String, String> map = MessageUtil.Dom2Map(result);
				if ("SUCCESS".equals(map.get("result_code"))) {
					// String rId =map.get("out_trade_no");
					itemOrder.setOrderState(7);
					itemOrderService.refuseOrder(itemOrder);
					/*
					 * ItemOrder o = new ItemOrder(); o.setId(itemOrder.getId());
					 * o.setOrderState(7); itemOrderService.updataOrder(o);
					 */
					rs = "/phone/refuse_sucess";
					}
			}else{
				rs = "/phone/refuse_error";
			}
		}
		return rs;
	}

	/**
	 * 根据订单状态查询
	 * 
	 * @param res
	 * @param state
	 * @param start
	 * @param size
	 * @return
	 */
	@RequestMapping("/phone/orderSearch")
	public String listOrder(HttpServletRequest res, @RequestParam(name = "start", defaultValue = "1") Integer start,
							@RequestParam(name = "size", defaultValue = "100") Integer size,OrderVo vo) {
		String result = "phone/order_list";
		User u = (User) res.getSession().getAttribute("u");
		if (StringUtils.isNotBlank(u.getId())) {
			vo.setUserId(u.getId());
			List<ItemOrder> list = itemOrderService.listItemOrderVo(vo, start, size);
			res.setAttribute("list", list);
		}
		return result;
	}

	/**
	 * 根据医生查询订单
	 * 
	 * @param id
	 * @param res
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/phone/doctor_order")
	public String doctorOrder(TimeVo vo, HttpServletRequest res,
			@RequestParam(name = "start", defaultValue = "1") Integer start,
			@RequestParam(name = "size", defaultValue = "100") Integer size) throws Exception {
			List<ItemOrder> list = null;
			if(!(StringUtils.isNotBlank(vo.getStartTime())&&StringUtils.isNotBlank(vo.getEndTime()))){
				vo.setStartTime(null);
				vo.setEndTime(null);
			}
			Map<String,Object> map = itemOrderService.listItemTimeVo(start, size, vo);
			list =(List<ItemOrder>) map.get("list"); 
			res.setAttribute("list", list);
			res.setAttribute("total", map.get("total"));
			res.setAttribute("sum", map.get("sum"));
		return "/phone/doctor_order";
	}

	@RequestMapping("/phone/addOrderYaodian")
	public String addOrderYaodian(ItemOrder order) {
		itemOrderService.updataOrder(order);
		return "redirect:/phone/toOrder?id=" + order.getId();
	}
	/**
	 * 通过店员按时间统计
	 * @param start
	 * @param size
	 * @param request
	 * @return
	 */
	@RequestMapping("/phone/order_yaodian")
	public String orderdianYuan(@RequestParam(name = "start", defaultValue = "1") Integer start,
								@RequestParam(name = "size", defaultValue = "100") Integer size, 
								HttpServletRequest request, TimeVo vo) {
		User u = (User) request.getSession().getAttribute("u");
		List<DianyuanOrderVo> list = null;
		if (u != null) {
			vo.setId(u.getId());
			if(StringUtils.isNotBlank(vo.getStartTime())&&StringUtils.isNotBlank(vo.getEndTime())){
				vo.setStartTime(vo.getStartTime()+":00");
				vo.setEndTime(vo.getEndTime()+":00");
			}
			Map<String,Object> map= itemOrderService.selectByDianyuan(start, size, vo);
			list =(List<DianyuanOrderVo>) map.get("list");
			request.setAttribute("total", map.get("total"));
			request.setAttribute("sum", map.get("sum"));
			request.setAttribute("list", list);
		}
		
		
		return "phone/order_dianyuan";
	}

	/**
	 * 取货
	 */
	@RequestMapping("/phone/orderStateChange")
	public String qiuYao(ItemOrder order) {
		order.setOrderState(4);
		itemOrderService.updataOrder(order);
		return "phone/qiuyaoOk";
	}

	/**
	 * 通过药店查询
	 * 
	 * @param res
	 * @param yaoId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/phone/yaodian_order")
	public String yaodianGetOrder(HttpServletRequest res, TimeVo vo,
								  @RequestParam(name = "start", defaultValue = "1") Integer start,
								  @RequestParam(name = "size", defaultValue = "100") Integer size) throws Exception {
		List<ItemOrder> list = null;
		if(!(StringUtils.isNotBlank(vo.getStartTime())&&StringUtils.isNotBlank(vo.getEndTime()))){
			vo.setStartTime(null);
			vo.setEndTime(null);
		}
		Map<String,Object> map = itemOrderService.listItemTimeVo(start, size, vo);
		list =(List<ItemOrder>) map.get("list"); 
		res.setAttribute("list", list);
		res.setAttribute("total", map.get("total"));
		res.setAttribute("sum", map.get("sum"));
		res.setAttribute("list", list);
		return "phone/yaodian_order";
	}

	/**
	 * 查询订单支付结果
	 * 
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/admin/queryResult")
	@ResponseBody
	public MyResult queryOrder(String orderId) throws Exception {
		MyResult rs = new MyResult();
		Pay pay = new Pay();
		pay.setAppid(appId);
		pay.setMch_id(mchId);
		pay.setOut_trade_no(orderId);
		String xml = PayUtil.queryPay(pay, key);
		Map<String, String> map = MessageUtil.Dom2Map(xml);
		if (StringUtils.isNotBlank(map.get("result_code")) && "SUCCESS".equals(map.get("result_code"))) {
			log.info("result_code:" + map.get("result_code"));
			String trade_state = map.get("trade_state");
			if (StringUtils.isNotBlank(trade_state)) {
				rs.setCash_fee(map.get("cash_fee"));
				rs.setOut_trade_no(map.get("out_trade_no"));
				rs.setTrade_state(map.get("trade_state"));
			}
		}
		return rs;
	}

	/**
	 * 通过医生分析
	 * 
	 * @param start
	 * @param size
	 * @param myDate
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/doctorAnlayzy")
	public String getOrderUser(@RequestParam(name = "start", defaultValue = "1") Integer start,
							   @RequestParam(name = "size", defaultValue = "10") Integer size, 
			                   String beginTime,String endTime,String doctorName,HttpServletRequest request) {
		Map<String,String> map =new HashMap<>();
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			map.put("beginTime","2018-01-01 00:00:00");
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("doctorName",doctorName);
		Map<String,Object> resultMap = itemOrderService.selectByDoctor(start, size, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		int total = list.size() / 10 + 1;
		request.setAttribute("page", start);
		request.setAttribute("total", total);
		request.setAttribute("list", list);
		return "jsp/doctorFenxi";
	}

	/**
	 * 通过药店分析
	 * 
	 * @param start
	 * @param size
	 * @param myDate
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/yaodianAnlayzy")
	public String getOrderGoods(@RequestParam(name = "start", defaultValue = "1") Integer start,
								@RequestParam(name = "size", defaultValue = "10") Integer size, 
								String beginTime,String endTime,String houseName,HttpServletRequest request) {
		Map<String,String> map =new HashMap<>();
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			map.put("beginTime","2018-01-01 00:00:00");
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("houseName",houseName);
		Map<String,Object> resultMap = itemOrderService.selectByYaodian(start, size, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		int total = list.size() / 10 + 1;
		request.setAttribute("page", start);
		request.setAttribute("total", total);
		request.setAttribute("list", list);
		return "jsp/yaodianFenxi";
	}
	/**
	 * 通过销售员分析
	 * @param start
	 * @param size
	 * @param beginTime
	 * @param endTime
	 * @param saleMan
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/saleManAnlayzy")
	public String getOrderSaleMan(@RequestParam(name = "start", defaultValue = "1") Integer start,
								  @RequestParam(name = "size", defaultValue = "10") Integer size, 
								String beginTime,String endTime,String saleMan,HttpServletRequest request) {
		Map<String,String> map =new HashMap<>();
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			map.put("beginTime","2018-01-01 00:00:00");
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("saleMan",saleMan);
		Map<String,Object> resultMap = itemOrderService.selectBySaleMan(start, size, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		int total = list.size() / 10 + 1;
		request.setAttribute("page", start);
		request.setAttribute("total", total);
		request.setAttribute("list", list);
		return "jsp/saleManFenxi";
	}

	/**
	 * 下载excel表格
	 * 
	 * @param res
	 * @param req
	 * @throws Exception
	 */
	@RequestMapping("/admin/exportExcel")
	public void exportExcel(String beginTime,String endTime,
							String doctorName,HttpServletResponse req) throws Exception {
		
		Map<String,String> map =new HashMap<>();
		if(StringUtils.isNotBlank(doctorName)){
			doctorName = new String(doctorName .getBytes("iso8859-1"),"utf-8"); 
		}
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			beginTime="2018-01-01 00:00:00";
			map.put("beginTime",beginTime);
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("doctorName",doctorName);
		Map<String,Object> resultMap = itemOrderService.selectByDoctor(1, 60000, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		List<String> header = new ArrayList<>();
		header.add("订单号");
		header.add("产品名称");
		header.add("订单总价");
		header.add("购买数量");
		header.add("医生姓名");
		header.add("收货人");
		header.add("联系电话");
		header.add("联系地址");
		header.add("配送方式");
		header.add("药店名称");
		header.add("药店地址");
		header.add("购买人电话");
		HSSFWorkbook wb = CommonUtis.exportExcel(header, list, "医生销量分析表");
		String fileName=new String((beginTime+"-"+endTime+"医生销量分析表.xls").getBytes(),"ISO-8859-1");
		OutputStream output = req.getOutputStream();
		req.reset();
		req.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		req.setContentType("application/msexcel");
		wb.write(output);
		output.close();
	}
	
	@RequestMapping("/admin/exportYaodianExcel")
	public void exportYaodianExcel(String beginTime,String endTime,
							String houseName,HttpServletResponse req) throws Exception {
		
		Map<String,String> map =new HashMap<>();
		if(StringUtils.isNotBlank(houseName)){
			houseName = new String(houseName .getBytes("iso8859-1"),"utf-8"); 
		}
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			beginTime="2018-01-01 00:00:00";
			map.put("beginTime",beginTime);
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("houseName",houseName);
		Map<String,Object> resultMap = itemOrderService.selectByYaodian(1, 60000, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		List<String> header = new ArrayList<>();
		header.add("订单号");
		header.add("产品名称");
		header.add("订单总价");
		header.add("购买数量");
		header.add("医生姓名");
		header.add("收货人");
		header.add("联系电话");
		header.add("联系地址");
		header.add("配送方式");
		header.add("药店名称");
		header.add("药店地址");
		header.add("购买人电话");
		HSSFWorkbook wb = CommonUtis.exportExcel(header, list, "药店销量分析表");
		String fileName=new String((beginTime+"-"+endTime+"药店销量分析表.xls").getBytes(),"ISO-8859-1");
		OutputStream output = req.getOutputStream();
		req.reset();
		req.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		req.setContentType("application/msexcel");
		wb.write(output);
		output.close();
	}
	
	@RequestMapping("/admin/exportSaleManExcel")
	public void exportGoodsExcel(String beginTime,String endTime,
								 String saleMan,HttpServletResponse req) throws Exception {
		Map<String,String> map =new HashMap<>();
		if(StringUtils.isNotBlank(saleMan)){
			saleMan = new String(saleMan .getBytes("iso8859-1"),"utf-8"); 
		}
		if (StringUtils.isNotBlank(beginTime)&&StringUtils.isNotBlank(endTime)) {
			map.put("beginTime",beginTime);
			map.put("endTime",endTime);
		}else{
			beginTime="2018-01-01 00:00:00";
			map.put("beginTime",beginTime);
			endTime =CommonUtis.formateDate("yyyy-MM-dd HH:mm:ss", new Date());
			map.put("endTime",endTime);
		}
		map.put("saleMan",saleMan);
		Map<String,Object> resultMap = itemOrderService.selectBySaleMan(1, 60000, map);
		List<OrderReturnVo> list =(List<OrderReturnVo>) resultMap.get("list");
		List<String> header = new ArrayList<>();
		header.add("订单号");
		header.add("产品名称");
		header.add("订单总价");
		header.add("购买数量");
		header.add("医生姓名");
		header.add("收货人");
		header.add("联系电话");
		header.add("联系地址");
		header.add("配送方式");
		header.add("药店名称");
		header.add("药店地址");
		header.add("购买人电话");
		header.add("销售员姓名");
		HSSFWorkbook wb = CommonUtis.exportGoodsExcel(header, list, "销售员销量分析");
		String fileName=new String((beginTime+"-"+endTime+"销售员销量分析表.xls").getBytes(),"ISO-8859-1");
		OutputStream output = req.getOutputStream();
		req.reset();
		req.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
		req.setContentType("application/msexcel");
		wb.write(output);
		output.close();
	}
	/**
	 * 取药页面
	 * @param code
	 * @param state
	 * @param res
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/orderTake")
	public String userAuthor(String code, String state, HttpServletRequest res, String orderId) throws Exception {
		String ss = WeiXinUtils.getWebAuthorToken(appId, appSecret, code);
		String result = "phone/quyao";
		log.info("userAuthorInfo:" + ss);
		WebAuthorToken info = JSON.parseObject(ss, WebAuthorToken.class);
		User u = userService.selectByOpenId(info.getOpenid());
		OrderVo vo =new OrderVo();
		vo.setId(orderId);
		List<OrderReturnVo> list= itemOrderService.selectByDefindId(vo);
		OrderReturnVo  item=null;
		if(list!=null&&list.size()>0){
			item=list.get(0);
		}
		if(item.getOrderState()!=3){
			result="";
			throw new Exception("订单已经取走!");
		}
		if (StringUtils.isNotBlank(item.getOrderYuliu())) {
			Yaodian yao = yaodianService.selectById(Integer.parseInt(item.getOrderYuliu()));
			if (yao.getHousePerson().equals(u.getRealName())) {
				res.getSession().setAttribute("u", u);
				res.setAttribute("order",item);
			}else {
				result="";
				throw new Exception("你不是店员");
			}
		} 
		return result;
	}
	/**
	 * 确认取药
	 * @param orderId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/phone/getYao")
	public String getGoodsByDianyuan(String orderId) throws Exception{
		ItemOrder item =itemOrderService.selectById(orderId);
		item.setOrderState(6);
		itemOrderService.updataOrder(item);
		User uu =userService.selectById(item.getOrderOwner());
		AccessToken access=userService.selectToken();
		String accessToken="";
		String rs ="";
		if(access==null||StringUtils.isBlank(access.getAccessToken())){
			 rs=HttpClientUtil.getAccessToken(appId, appSecret);
			 if(rs.indexOf("error") < 0){
				AccessToken token =JSON.parseObject(rs, AccessToken.class);
				accessToken =token.getAccessToken();
				token.setCreateTime(new Date());
				userService.insertToken(token);
			}
			
		}else if(CommonUtis.isDisable(access)){
			rs =HttpClientUtil.getAccessToken(appId, appSecret);
			if(rs.indexOf("error") < 0){
				AccessToken token =JSON.parseObject(rs, AccessToken.class);
				token.setId(access.getId());
				token.setCreateTime(new Date());
				userService.updateToken(token);
				accessToken =token.getAccessToken();
			}
		}else{
			accessToken=access.getAccessToken();
		}
		Map<String,TemplateData> map =new HashMap<>();
		TemplateData first =new TemplateData();
		first.setColor("#000000");
		first.setValue("您的药品已经被取走!");
		TemplateData keyword1 =new TemplateData();
		keyword1.setColor("#000000");
		keyword1.setValue(orderId);
		TemplateData keyword2 =new TemplateData();
		keyword2.setColor("#000000");
		keyword2.setValue(item.getGoodsName());
		TemplateData keyword3 =new TemplateData();
		keyword3.setColor("#000000");
		keyword3.setValue(uu.getWeName());
		TemplateData keyword4 =new TemplateData();
		keyword4.setColor("#000000");
		keyword4.setValue(CommonUtis.formateDate("yyyy-MM-dd hh:mm:ss", new Date()));
		TemplateData remark =new TemplateData();
		remark.setColor("#000000");
		remark.setValue("请确认是否本人取走!");
		map.put("first", first);
		map.put("keyword1", keyword1);
		map.put("keyword2", keyword2);
		map.put("keyword3", keyword3);
		map.put("keyword4", keyword4);
		map.put("remark", remark);
		WeiXinUtils.sendTempleteMsg(accessToken, uu.getName(), template_id,map);
		return "phone/qiuyao_success";
	}
	/**
	 * 后台查询订单详情
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/orderDetail")
	public String getOrderDetail(OrderVo vo,HttpServletRequest request){
		List<OrderReturnVo> list =itemOrderService.selectByDefindId(vo);
		if(list!=null&&list.size()>0){
			request.setAttribute("order", list.get(0));
		}
		return "jsp/order_detail";
	}
	/**
	 * 后台查询订单情况
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/phone/orderDetail")
	public String getPhoneOrder(OrderVo vo,HttpServletRequest request){
			List<OrderReturnVo> list =itemOrderService.selectByDefindId(vo);
			if(list!=null&&list.size()>0){
				request.setAttribute("order", list.get(0));
			}
		return "phone/order_detail";
	}
	/**
	 * 更新处方
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/phone/reChufang")
	public String reChufang(String id,HttpServletRequest request){
		if(StringUtils.isNotBlank(id)){
			ItemOrder order =itemOrderService.selectById(id);
			request.setAttribute("order", order);
		}
		return "phone/re_chufang";
	}
	/**
	 * 更新处方
	 * @param order
	 * @return
	 */
	@RequestMapping("/phone/updateOrder")
	public String updateChufang(ItemOrder order){
		order.setOrderState(2);
		itemOrderService.updataOrder(order);
		return "phone/update_success";
	}
	
	/**
	 * 退款页面
	 * @param res
	 * @param orderId
	 * @return
	 */
	@RequestMapping("/phone/tuiSure")
	public String tuiSure(HttpServletRequest res,String orderId){
		res.setAttribute("orderId", orderId);
		return "phone/tui_sure";
	}
	/**
	 * 购物车一起支付
	 * @param res
	 * @param id
	 * @return
	 */
	@RequestMapping("/phone/cartOrder")
	@ResponseBody
	public String cartToOrder(HttpServletRequest res,String buys){
		List<Cart> list =new ArrayList<>();
		StringBuffer result= new StringBuffer();
		String rs ="error";
		try {
			if(StringUtils.isNotBlank(buys)&&buys.endsWith(",")){
				String ids [] =(buys.substring(0,buys.length()-1)).split(",");
				for(String id :ids){
					Cart cart =cartService.selectById(Integer.parseInt(id));
					list.add(cart);
				}
			}else{
				Cart cart =cartService.selectById(Integer.parseInt(buys));
				list.add(cart);
			}
			List<ItemOrder> orders= cartToItemOrder(list);
			for(ItemOrder order:orders){
				result.append(itemOrderService.insertOrder(order)).append(",");
			}
			rs=result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			rs="error";
		}
		return rs;
	}
	/**
	 * 购物车单个支付
	 * @param res
	 * @param id
	 * @return
	 */
	@RequestMapping("/phone/cartOneOrder")
	@ResponseBody
	public String cartOneOrder(HttpServletRequest res,Integer id){
		String rs="error";
			try {
				Cart cart =cartService.selectById(id);
				if(cart!=null){
					ItemOrder itemOrder =new ItemOrder();
					itemOrder.setGoodsId(cart.getGoodsId());
					itemOrder.setGoodsPic(cart.getGoodsPic());
					itemOrder.setOrderSum(cart.getGoodsNumber());
					itemOrder.setOrderPrice(cart.getGoodsPrice());
					itemOrder.setOrderMonth(PayUtil.getMonth());
					itemOrder.setGoodsName(cart.getGoodsName());
					itemOrder.setOrderState(0);
					rs =itemOrderService.insertOrder(itemOrder);
					cartService.deleteCart(id);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		return rs;
	}
	/**
	 * 将购物车转化成订单
	 * @param list
	 * @return
	 */
	private List<ItemOrder> cartToItemOrder(List<Cart> list) {
		List<ItemOrder> orders =new ArrayList<>();
		String pId ="P"+CommonUtis.creatOrderId();
		for(Cart cart :list){
			ItemOrder itemOrder =new ItemOrder();
			itemOrder.setGoodsId(cart.getGoodsId());
			itemOrder.setGoodsPic(cart.getGoodsPic());
			itemOrder.setOrderSum(cart.getGoodsNumber());
			itemOrder.setOrderPrice(cart.getGoodsPrice());
			itemOrder.setOrderTotal(cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNumber())));
			itemOrder.setOrderMonth(PayUtil.getMonth());
			itemOrder.setGoodsName(cart.getGoodsName());
			itemOrder.setOrderState(0);
			itemOrder.setOrderPrepare(pId);
			orders.add(itemOrder);
		}
		return orders;
	}

	/**
	 * 获取订单的取货码
	 * @param res
	 * @param id
	 * @return
	 */
	@RequestMapping("/phone/getCode")
	public String getVcode(HttpServletRequest res,String id){
		if(StringUtils.isNotBlank(id)){
			ItemOrder order =itemOrderService.selectById(id);
			if(StringUtils.isNotBlank(order.getOrderTest())){
				res.setAttribute("order", order);
			}
		}
		return "phone/tupian";
	}
}
